package com.mediastory.spsserver.advertising.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mediastory.spsserver.adCategory.service.AdCategorySvc;
import com.mediastory.spsserver.adFile.service.AdFileSvc;
import com.mediastory.spsserver.advertising.domain.Advertising;
import com.mediastory.spsserver.advertising.service.AdvertisingSvc;
import com.mediastory.spsserver.category.service.CategorySvc;
import com.mediastory.spsserver.content.service.ContentSvc;
import com.mediastory.spsserver.event.service.EventSvc;

/**
 * @author Jaewon Choi
 */

@Controller
@RequestMapping(value={"/ad"})
public class AdvertisingCtrl {
	
	private final Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private AdvertisingSvc advertisingSvc;
	
	@Autowired
	private AdFileSvc adFileSvc;
	
	@Autowired
	private AdCategorySvc adCategorySvc;
	
	@Autowired
	private ContentSvc contentSvc;
	
	@Autowired
	private EventSvc eventSvc;
	
	@Autowired
	private CategorySvc categorySvc;

	/**
	 * 목록 보기
	 * */
	@RequestMapping(value={"/list.do"})
	public Map<String, Object> list(HttpServletRequest request, HttpSession session) throws Exception {
		Map<String, Object> condition = new HashMap<String, Object>();
		//검색 parameter
		String name = ServletRequestUtils.getStringParameter(request, "name");
		String title = ServletRequestUtils.getStringParameter(request, "title");
		String startDate = ServletRequestUtils.getStringParameter(request, "startDate");
		String endDate = ServletRequestUtils.getStringParameter(request, "endDate");
		String adCategoryIdx = ServletRequestUtils.getStringParameter(request, "adCategoryIdx");
		String categoryIdx = ServletRequestUtils.getStringParameter(request, "categoryIdx");
		
		
		//contentIdx
		Integer cIdx = (Integer)session.getAttribute("cIdx");
		
		condition.put("name", name);
		condition.put("title", title);
		condition.put("startDate", startDate);
		condition.put("endDate", endDate);
		condition.put("adCategoryIdx", adCategoryIdx);
		condition.put("cIdx", cIdx);
		condition.put("categoryIdx", categoryIdx);

		//페이징 처리 parameter
		int maxnum = ServletRequestUtils.getIntParameter(request, "maxnum", 10);
		int page = ServletRequestUtils.getIntParameter(request, "page", 1);
		condition.put("maxnum", maxnum);
		condition.put("page", (page-1)*maxnum);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.putAll(advertisingSvc.findbyListPaging(condition));
		resultMap.put("adCategoryList", adCategorySvc.findbyList(null));
		resultMap.put("maxnum", maxnum);
		resultMap.put("page", page);
		
		//카테고리 목록
		resultMap.put("categoryList", categorySvc.findbyList(null));
		
		return resultMap;
	}

	/**
	 * 상세 보기
	 * */
	@RequestMapping(value={"/detail.do"})
	public Map<String, Object> detail(HttpServletRequest request, HttpSession session, @RequestParam(required=true, value="idx")  Integer idx) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		Map<String, Object> condition = new HashMap<String, Object>();

		//콘텐츠 목록
		resultMap.put("contList", contentSvc.findbyList(condition));
		
		//이벤트 목록
		resultMap.put("eventList", eventSvc.findbyList(condition));
		
		//카테고리 검색 조건
		condition.put("idx", idx);
		resultMap.put("advertising", advertisingSvc.findby(condition));
		
		//상세 보기일 경우 콘텐츠의 id를 조건으로 카테고리를 조회하여 어느 카테고리에 포함는지를 표시하기 위함. 
		condition.put("adIdx", idx);
		
		//카테고리 목록
		resultMap.put("adCategoryList", adCategorySvc.findbyList(condition));

		//파일 조회
		resultMap.put("adFileList", adFileSvc.findbyList(condition));

		return resultMap;
	}
	
	/**
	 * 등록,수정 폼
	 * */
	@RequestMapping(value={"/form.do"})
	public Map<String, Object> form(HttpServletRequest request, HttpSession session) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		

		Map<String, Object> condition = new HashMap<String, Object>();
		//콘텐츠 목록
		resultMap.put("contList", contentSvc.findbyList(condition));
		
		//이벤트 목록
		resultMap.put("eventList", eventSvc.findbyList(condition));
		
		int idx = ServletRequestUtils.getIntParameter(request, "idx", 0);
		if(idx != 0){
			//광고
			condition.put("idx", idx);
			resultMap.put("advertising", advertisingSvc.findby(condition));
			
			//상세 보기일 경우 광고의 idx를 조건으로 카테고리를 조회하여 어느 카테고리에 포함는지를 표시하기 위함. 
			condition.put("adIdx", idx);
			
			//파일 조회
			resultMap.put("adFileList", adFileSvc.findbyList(condition));
		}
		
		//카테고리 목록
		resultMap.put("adCategoryList", adCategorySvc.findbyList(condition));
		
		//카테고리 목록
		resultMap.put("categoryList", categorySvc.findbyList(null));


		return resultMap;
	}
	
	/**
	 * 등록/수정
	 * */
	@RequestMapping(value={"/submit.do"}, method=RequestMethod.POST)
	public String submit(Advertising advertising, HttpServletRequest request, HttpSession session) throws Exception {
		String userId = (String)session.getAttribute("userId");
		String ip = request.getRemoteAddr();
		
		if(advertising.getIdx() != null){
			advertising.setModifiedId(userId);
			advertising.setModifiedIp(ip);
			advertisingSvc.modify(advertising);
		}else{
			advertising.setCreatedId(userId);
			advertising.setCreatedIp(ip);
			advertisingSvc.add(advertising);
		}

		return "ad/result";
	}
	
	/**
	 * 삭제
	 * */
	@RequestMapping(value={"/remove.do"}, method=RequestMethod.POST)
	public String remove(HttpServletRequest request, HttpSession session) throws Exception {
		String userId = (String)session.getAttribute("userId");
		String ip = request.getRemoteAddr();
		
		int[] idx = ServletRequestUtils.getIntParameters(request, "idx");
		
		Map<String, Object> condition = new HashMap<String, Object>();
		
		condition.put("modifiedId", userId);
		condition.put("modifiedIp", ip);
		condition.put("idx", idx);
		
		advertisingSvc.remove(condition);
		return "ad/result";
	}
	
	/**
	 * 중복 체크
	 * */
	@RequestMapping(method=RequestMethod.POST, value="/chkDupl")
	public @ResponseBody Map<String, Object> chkDupl(HttpSession session, @RequestParam(required=true, value="idx")  Integer idx, @RequestParam(required=true, value="chkName")  String name) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("idx", idx);
			condition.put("chkName", name);

			String result = advertisingSvc.findbyChkDupl(condition);
			
			resultMap.put("resultCode", "200");
			resultMap.put("result", result);
		} catch (Exception e) {
			// TODO: handle exception
			//e.printStackTrace();
			logger.error(e.getMessage(), e);
			resultMap.put("resultCode", "500");
			resultMap.put("errMsg", "Error");
		}

		return resultMap;
	}
}